var db           = require('../../config/mongo_database');
var logger       = require('../../config/log4js').logger('access');
var property     = require('../../route/property');
var tokenManager = require('../../config/token_manager');

// 充值订单// 0 购买 1 充值 2提现 3赎回到账
exports.chonglist = function(req, res){
	var username    = req.body.username || '';
	var orderid     = req.body.orderid  || '';
	var pages       = req.body.pages     || 0;

	var where  = { type:'1'};
	if(username != '')
		where.username = username
	if(orderid != '')
		where.orderid  = orderid
	
	db.balanceModel.count(where, function(err, count){
		db.balanceModel
		.where(where)
		.skip(pages*20)
		.limit(20)
		.sort({ status : -1, updated:-1 })
		.exec(function(err, list){
			return res.json({status:200, count:count, list:list});
		})
	})
}

// 提现订单
exports.tixianlist = function(req, res){
	var username    = req.body.username || '';
	var orderid     = req.body.orderid  || '';
	var pages       = req.body.pages     || 0;

	var where  = { type:'2'};
	if(username != '')
		where.username = username
	if(orderid != '')
		where.orderid  = orderid
	
	db.balanceModel.count(where, function(err, count){
		db.balanceModel
		.where(where)
		.skip(pages*20)
		.limit(20)
		.sort({ status : -1, updated:-1 })
		.exec(function(err, list){
			return res.json({status:200, count:count, list:list});
		})
	})
}

// 确认提现
exports.confirmTixian = function(req, res){
	var orderid = req.body.orderid  || '';
	var saddr   = req.body.saddr    || '';  //发送地址 

	//查询更新订单并打款
	db.balanceModel.findOne({orderid:orderid, status:'0'}, function(err, balance){
		if(err || balance==null){
			logger.error('balance.confirmTixian没有查询到', orderid)
			return res.json({status:400, msg:'未查询到该笔订单'})
		}else{
			db.balanceModel.update({orderid:orderid}, {$set:{status:'1', saddr:saddr, updated:new Date()}}, function(err){
				if(err){
					logger.error('balance.confirmTixian更新对账单失败', orderid)
					return res.json({status:400, msg:'更新失败'})
				}else{
					return res.json({status:200, msg:'更新对账单成功'})
				}
			})
		}	
	})

}

/*****
    提现金额校验
	获取用户金额，
 ****/
exports.validate = function(req, res){
	var orderid = req.body.orderid  || '';

	console.log('-----------------', orderid)

	db.balanceModel.findOne({orderid:orderid, status:'0'}, function(err, balance){
		var where1 = {username:balance.username, status:'1'}
		var where2 = {username:balance.username, status:'0', type:'2'}
		db.walletModel.findOne({userid: balance.userid, btype:balance.btype}, function(err, wallet){
			if(err || wallet==null){
				logger.error('未查询到钱包', balance)
				return res.json({status:502, msg:'订单校验异常'})
			}else{
				db.balanceModel.aggregate([{$match:where1}, {"$group":{_id: '$userid', ytotal:{"$sum":"$countn"}}}], function(e, doc){ // 合计
					if(err || doc.length==0){
						return res.json({status:503, msg:'订单校验异常'})
					}else{
						db.balanceModel.aggregate([{$match:where2}, {"$group":{_id: '$userid', ttotal:{"$sum":"$countn"}}}], function(e, result){
							if(err || result.length==0){
								return res.json({status:504, msg:'订单校验异常'})
							}
							console.log(doc[0]['ytotal'], result[0]['ttotal'], wallet.asset)
							if((Number(doc[0]['ytotal']) + Number(result[0]['ttotal']) ) == Number(wallet.asset)){
								return res.json({status:200, msg:'校验成功'})
							}else{
								db.balanceModel.update({orderid: balance.orderid, status:'0'}, {$set:{status:'3'}}, function(err){

								})
								return res.json({status:505, msg:'该笔交易存在异常'});
							}
						})	
					}
				})
			}
		})
	})

}


// 确认充值
exports.confirmChong = function(req, res){
	var orderid = req.body.orderid  || '';

	//查询更新订单并打款
	db.balanceModel.findOne({orderid:orderid, status:'0'}, function(err, balance){
		if(err || balance==null){
			logger.error('balance.confirmChong没有查询到', orderid)
			return res.json({status:400, msg:'未查询到该笔订单'})
		}else{
			db.balanceModel.update({orderid:orderid}, {$set:{status:'1', updated:new Date()}}, function(err){
				if(err){
					logger.error('balance.confirmChong更新对账单失败', orderid)
					return res.json({status:400, msg:'更新对账单失败'})
				}else{
					db.walletModel.update({userid:balance.userid, btype:balance.btype}, {$inc: {asset:balance.pay}}, function(err){
						if(err){
							logger.error('balance.confirmChong更新金额失败', balance.userid, balance.btype)
							return res.json({status:400, msg:'更新金额失败'})
						}else{
							return res.json({status:200, msg:'充值成功'})
						}
					})
				}
			})
		}	
	})

}


// 订单关闭
exports.excpChong = function(req, res){
	var orderid = req.body.orderid  || '';

	//查询更新订单(2为订单关闭)
	db.balanceModel.findOne({orderid:orderid, status:'0'}, function(err, balance){
		if(err || balance==null){
			logger.error('balance.excpChong没有查询到', orderid)
			return res.json({status:400, msg:'未查询到该笔订单'})
		}else{
			db.balanceModel.update({orderid:orderid}, {$set:{status:'2', updated:new Date()}}, function(err){
				if(err){
					logger.error('balance.excpChong更新对账单失败', orderid)
					return res.json({status:400, msg:'更新对账单失败'})
				}else{
					return res.json({status:200, msg:'关闭成功'})
				}
			})
		}	
	})

}